package com.naodong.shenluntiku.mvp.view.webView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;


import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;

import java.net.URLDecoder;

/**
 * Created by hujie on 17/5/12.
 */

public class TKWebViewClient extends BridgeWebViewClient {

    TKWebViewListener tkWebViewListener;

    private String requestUrl;
    private boolean isShowErrorPage;

    public TKWebViewClient(BridgeWebView webView) {
        super(webView);
    }

    public void setTkWebViewListener(TKWebViewListener tkWebViewListener) {
        this.tkWebViewListener = tkWebViewListener;
    }


    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        try {
            // 如下方案可在非微信内部WebView的H5页面中调出微信支付
            if (url.startsWith("weixin://wap/pay?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                view.getContext().startActivity(intent);
                return true;
            }
        } catch (Exception e) {
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if (!isShowErrorPage) {
            view.setVisibility(View.VISIBLE);
        }
        if (tkWebViewListener != null) {
            tkWebViewListener.setReceiveTitle(view.getTitle());
            tkWebViewListener.onPageFinished();
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (tkWebViewListener != null) {
            tkWebViewListener.showProgress();
        }
        this.isShowErrorPage = false;
        this.requestUrl = url;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        if (failingUrl != null && failingUrl.equals(requestUrl)) {
            if (ERROR_HOST_LOOKUP == errorCode || ERROR_CONNECT == errorCode || ERROR_IO == errorCode || ERROR_TIMEOUT == errorCode) {
                if (tkWebViewListener != null) {
                    view.setVisibility(View.INVISIBLE);
                    tkWebViewListener.showErrorPage();
                }
                isShowErrorPage = true;
            }
        }
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
    }
}
